﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VSWClient.Tcp;
using VSWClient.Utility;
using System.Data;
using VSWClient.Export;
using VSWClient.Tables;
using VSWClient.Pages.Tables.L2PDB;
namespace VSWClient.Pages
{
    /// <summary>
    /// Page_Downtime.xaml interaction logic
    /// </summary>
    public partial class Page_Downtime : UserControl
    {
        TcpClient client;
		DataTable dataTableDownTimeExport = new DataTable();
		public int downtime_Index = 1;//downtime table data current page
		public int downtime_Pagenum = 20;//numbers of downtime table data per page
		public bool downtime_index_isChange = true;//
		string finddowntimeSql = "";
		string predowntimeNo;
		DateTime prestartTime;
		DateTime preendTime;
		public Page_Downtime(TcpClient tcp)
        {
            InitializeComponent();
            client = tcp;			
		}
		#region Window loaded
		private void PageDowntime_Loaded(object sender, RoutedEventArgs e)
		{
			try
			{
				client.SendMessage(Identity.definedCommand, Identity.innitPageDownTime, "");
				downtime_Index = 1;
				textBox_DownTimePage.Text = downtime_Index.ToString();
				this.dateTimePickerstarttime.Value = Convert.ToDateTime("00:00:00");
				//this.dateTimePickerendtime.Value = Convert.ToDateTime("23:59:59");
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("PageDowntime_Loaded", ex);
			}
			
		}
		#endregion

		#region downtime refresh
		public void RefreshPageDownTimeList(DataTable dataTable)
		{
			try
			{
				if (dataTable.TableName == DOWNTIME_TABLE.tableName)
				{
					if (dataTable != null && dataTable.Rows.Count > 0)
					{
						DataRow[] dataRows = dataTable.Select(string.Format("{0} is not null", DOWNTIME_TABLE.fd_startTime), string.Format("{0} asc", DOWNTIME_TABLE.fd_startTime));
						if (dataRows.Length > 0)
						{
							dataTableDownTimeExport = null;
							dataTableDownTimeExport = dataRows.CopyToDataTable();
						}
					}
					DataGrid_DownTime.ItemsSource = dataTable.DefaultView;

					Style l_textStyle = new Style(typeof(TextBlock));
					l_textStyle.Setters.Add(new Setter(TextBlock.TextWrappingProperty, TextWrapping.Wrap));
					DataGridTextColumn dg = DataGrid_DownTime.Columns[8] as DataGridTextColumn;
					dg.MaxWidth = 300;
					dg.ElementStyle = l_textStyle;
					DataGridTextColumn dg10 = DataGrid_DownTime.Columns[10] as DataGridTextColumn;
					dg10.MaxWidth = 300;
					dg10.ElementStyle = l_textStyle;

				}
				else if (dataTable.TableName == TEAM_TABLE.tableName)
				{
					if (dataTable != null && dataTable.Rows.Count > 0)
					{
						//加载班组下拉框
						ComboBox_Shift.Items.Clear();
						for (int i = 0; i < TEAM_TABLE.teamtable.Rows.Count; i++)
						{
							ComboBox_Shift.Items.Add(TEAM_TABLE.teamtable.Rows[i][TEAM_TABLE.fd_dayShift].ToString());
						}
					}
				}
				LogHelper.WriteLog("RefreshPageDownTimeList");
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("RefreshPageDownTimeList", ex);
			}			
		}
		#endregion

		#region downtime  paging query
		/// <summary>
		/// query downtime
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_query_downtime_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				string selectStartTime = Convert.ToString(datePicker_StartTime.SelectedDate?.ToString(Formats.GetShortFormat()));
				string selectendTime = Convert.ToString(datePicker_EndTime.SelectedDate?.ToString(Formats.GetShortFormat()));
				string Starttime = Convert.ToString(datePicker_StartTime.SelectedDate?.ToString(Formats.GetShortFormat())) + " "
							  + Convert.ToString(dateTimePickerstarttime.Value.ToString(Formats.GetTimeFormat()));  //查询开始时间
				string Endtime = Convert.ToString(datePicker_EndTime.SelectedDate?.ToString(Formats.GetShortFormat())) + " "
							   + Convert.ToString(dateTimePickerendtime.Value.ToString(Formats.GetTimeFormat()));  //查询结束时间
				string strsql = string.Format("select ROWNUM rn,d.* from (select * from {0} where 1=1", DOWNTIME_TABLE.tableName);
				if (ComboBox_Shift.Text.ToString() != "")
				{
					strsql += string.Format(" and {0}='{1}'", DOWNTIME_TABLE.fd_shiftName, ComboBox_Shift.Text.ToString());
				}
				else
				{
					if (selectStartTime != null && selectendTime == null)
					{
						strsql += string.Format(" and {0} >='", DOWNTIME_TABLE.fd_startTime) + Starttime + string.Format("' and {0}<='", DOWNTIME_TABLE.fd_startTime) + selectStartTime + " 23:59:59'";
					}
					if (selectStartTime == null && selectendTime != null)
					{
						strsql += string.Format(" and {0} >='", DOWNTIME_TABLE.fd_startTime) + selectendTime + " 00:00:00" + string.Format("' and {0}<='", DOWNTIME_TABLE.fd_startTime) + Endtime + "'";
					}
					if (selectStartTime != null && selectendTime != null)
					{
						strsql += string.Format(" and {0} >='", DOWNTIME_TABLE.fd_startTime) + Starttime + string.Format("' and {0}<='", DOWNTIME_TABLE.fd_startTime) + Endtime + "'";
					}
					if (selectStartTime == null && selectendTime == null)
					{
						string starttime = DateTime.Now.Date.ToString(Formats.GetDateFormat());
						string endtime = DateTime.Now.ToString(Formats.GetDateFormat());
						strsql += string.Format(" and {0}>='", DOWNTIME_TABLE.fd_startTime) + starttime + string.Format("' and {0}<='", DOWNTIME_TABLE.fd_startTime) + endtime + "'";
					}
				}
				strsql +=string.Format(" order by {0} desc) d",DOWNTIME_TABLE.fd_updateTime);
				downtime_Index = 1;
				textBox_DownTimePage.Text = downtime_Index.ToString();
				finddowntimeSql = strsql;
				client.SendMessage(Identity.definedCommand, Identity.selectV7_DOWNTIME, finddowntimeSql + ";0;20");
				LogHelper.WriteLog("btn_query_downtime_Click");
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_query_downtime_Click", ex);
			}			
		}
		/// <summary>
		/// downtime page up
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_UpPage_DownTime_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				if (downtime_Index > 1)
				{
					downtime_Index--;
					textBox_DownTimePage.Text = downtime_Index.ToString();
					client.SendMessage(Identity.definedCommand, Identity.selectV7_DOWNTIME, finddowntimeSql + ";" + ((downtime_Index - 1) * downtime_Pagenum) + ";" + downtime_Index * downtime_Pagenum);
					LogHelper.WriteLog("btn_UpPage_Pipe_Click");
				}				
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_UpPage_Pipe_Click", ex);
				throw ex;
			}
		}
		/// <summary>
		/// downtime page down
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_DownPage_DownTime_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				if (Convert.ToInt32(textBox_DownTimePage.Text) < Convert.ToInt32(textBox_DownTimeTotalPages.Text))
				{
					downtime_Index++;
					textBox_DownTimePage.Text = downtime_Index.ToString();
					client.SendMessage(Identity.definedCommand, Identity.selectV7_DOWNTIME, finddowntimeSql + ";" + ((downtime_Index - 1) * downtime_Pagenum) + ";" + downtime_Index * downtime_Pagenum);
					LogHelper.WriteLog("btn_DownPage_DownTime_Click");
				}
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_DownPage_DownTime_Click", ex);
				throw ex;
			}
		}
		#endregion

		#region DownTime Export
		/// <summary>
		/// export downtime data
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_Export_downtime_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				if (dataTableDownTimeExport == null || dataTableDownTimeExport.Rows.Count > 0)
				{
					NPOIToExcel.ExportToExcel(dataTableDownTimeExport, System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/xls/DownTime_Record.xls", "Sheet1");
				}
				LogHelper.WriteLog("btn_Export_downtime_Click");
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_Export_downtime_Click", ex);
			}			
		}
		#endregion

		#region modify downtime record
		/// <summary>
		/// double click downtime table data
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void DataGrid_DownTime_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
		{
			try
			{
				popup_DownTime.IsOpen = true;
				var drvdowntime = DataGrid_DownTime.SelectedItem as DataRowView;
				if (drvdowntime != null)
				{
					string eventNo = drvdowntime.Row[DOWNTIME_TABLE.fd_eventNo].ToString();
					string downtimeNo = drvdowntime.Row[DOWNTIME_TABLE.fd_downtimeNo].ToString();
					string stopType = drvdowntime.Row[DOWNTIME_TABLE.fd_stopType].ToString();
					string machineNo = drvdowntime.Row[DOWNTIME_TABLE.fd_machineNo].ToString();
					string startTime = drvdowntime.Row[DOWNTIME_TABLE.fd_startTime].ToString();
					string endTime = drvdowntime.Row[DOWNTIME_TABLE.fd_endTime].ToString();
					string serviceTeam = drvdowntime.Row[DOWNTIME_TABLE.fd_serviceTeam].ToString();
					string stopReason = drvdowntime.Row[DOWNTIME_TABLE.fd_stopReason].ToString();
					string status = drvdowntime.Row[DOWNTIME_TABLE.fd_status].ToString();
					string downComment = drvdowntime.Row[DOWNTIME_TABLE.fd_downComment].ToString();
					string updateTime = drvdowntime.Row[DOWNTIME_TABLE.fd_updateTime].ToString();
					string shiftName = drvdowntime.Row[DOWNTIME_TABLE.fd_shiftName].ToString();
					string operateName = drvdowntime.Row[DOWNTIME_TABLE.fd_operateName].ToString();

					textBox_downtimeNo.Text = downtimeNo;
					textBox_stopType.Text = stopType;
					textBox_machineNo.Text = machineNo;
					textBox_startTime.Text = startTime;
					textBox_endTime.Text = endTime;
					textBox_serviceTeam.Text = serviceTeam;
					textBox_stopReason.Text = stopReason;
					textBox_status.Text = status;
					textBox_downComment.Text = downComment;
				}
				LogHelper.WriteLog("DataGrid_DownTime_PreviewMouseDoubleClick");
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("DataGrid_DownTime_PreviewMouseDoubleClick", ex);
			}
		
		}
		/// <summary>
		/// save downtime record
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_save_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				client.SendMessage(Identity.definedCommand, Identity.updatedowntime, textBox_downtimeNo.Text + ";" + textBox_stopType.Text + ";" + textBox_machineNo.Text +
					";" + textBox_startTime.Text + ";" + textBox_endTime.Text + ";" + textBox_serviceTeam.Text + ";" + textBox_stopReason.Text +
					";" + textBox_status.Text + ";" + textBox_downComment.Text + ";" + USER_TABLE.user_Name + ";" + USER_TABLE.user_No);
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_save_Click", ex);
			}			
		}
		/// <summary>
		/// close popup_downtime
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_close_Click(object sender, RoutedEventArgs e)
		{
			popup_DownTime.IsOpen = false;
		}
		#endregion

		#region split DownTime		
		/// <summary>
		/// split downtime button
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuItem_AddDowntime_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				
				var drvdowntime = DataGrid_DownTime.SelectedItem as DataRowView;
				if (drvdowntime != null)
				{
					predowntimeNo = drvdowntime.Row[DOWNTIME_TABLE.fd_downtimeNo].ToString();
					prestartTime = Convert.ToDateTime(drvdowntime.Row[DOWNTIME_TABLE.fd_startTime].ToString());
					preadddowntimeStarttime = prestartTime;
					if (!DateTime.TryParse(drvdowntime.Row[DOWNTIME_TABLE.fd_endTime].ToString(),out preendTime))
					{
						MessageBox.Show("downtime is not over yet and cannot be splited");
						return;
					}
					popup_AddDownTime.IsOpen = true;
					preendTime = Convert.ToDateTime(drvdowntime.Row[DOWNTIME_TABLE.fd_endTime].ToString());
					textBox_adddowntimeNo.Text = DateTime.Now.ToString(Formats.DowntimeIdFormat);
					this.dateTimePickeraddstarttime.Value = Convert.ToDateTime(prestartTime.ToString(Formats.GetTimeFormat()));
					datePicker_addStartTime.Text = prestartTime.ToString(Formats.GetShortFormat());
					this.dateTimePickeraddendtime.Value = Convert.ToDateTime(preendTime.ToString(Formats.GetTimeFormat()));
					datePicker_addEndTime.Text = preendTime.ToString(Formats.GetShortFormat());
					textBox_addstopType.Text = "";
					textBox_addmachineNo.Text = "";
					textBox_addserviceTeam.Text = "";
					textBox_addstopReason.Text = "";
					textBox_addstatus.Text = "";
					textBox_adddownComment.Text = "";
					textBox_addstopType.Text = "";
					textBox_addmachineNo.Text = "";
				}
				LogHelper.WriteLog("menuItem_AddDowntime_Click");
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("menuItem_AddDowntime_Click", ex);
			}
			
		}
		/// <summary>
		/// save split downtime record
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		DateTime preadddowntimeStarttime;
		private void btn_saveAddDowntime_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				if (textBox_addstopType.Text == "" || textBox_addmachineNo.Text == ""|| textBox_addserviceTeam.Text==""|| textBox_addstatus.Text=="")
				{
					MessageBox.Show("stoptype,machineNo,serviceTeam,status cannot be empty");
					return;
				}
				string starttime= datePicker_addStartTime.SelectedDate?.ToString(Formats.GetShortFormat())
					 + " " + Convert.ToString(dateTimePickeraddstarttime.Value.ToString(Formats.GetTimeFormat()));
				string endtime= datePicker_addEndTime.SelectedDate?.ToString(Formats.GetShortFormat())
					 + " " + Convert.ToString(dateTimePickeraddendtime.Value.ToString(Formats.GetTimeFormat()));
				DateTime startDatetime = Convert.ToDateTime(starttime);
				DateTime endDatetime = Convert.ToDateTime(endtime);
				if (startDatetime >= endDatetime)
				{
					MessageBox.Show("The start time cannot be greater than or equal to the end time");
					return;
				}
				else if (preadddowntimeStarttime>= startDatetime)
				{
					MessageBox.Show("The start time cannot be greater than or equal to the original start time");
					return;
				}
				DataTable dataTableDowntime = new DataTable();
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_eventNo, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_downtimeNo, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_stopType, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_machineNo, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_startTime, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_endTime, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_serviceTeam, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_stopReason, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_status, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_downComment, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_operateName, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_shiftName, typeof(string));
				dataTableDowntime.Columns.Add(DOWNTIME_TABLE.fd_updateTime, typeof(string));
				dataTableDowntime.Rows.Add("0", textBox_adddowntimeNo.Text, textBox_addstopType.Text, textBox_addmachineNo.Text, starttime, endtime, textBox_addserviceTeam.Text, textBox_addstopReason.Text, textBox_addstatus.Text, textBox_adddownComment.Text, USER_TABLE.user_Name,"","");
				client.SendMessage(Identity.definedCommand, Identity.adddowntime,
					predowntimeNo + ";"+ JsonHelper.SerializeObject(dataTableDowntime) + ";" + USER_TABLE.user_No);

				client.SendMessage(Identity.definedCommand, Identity.adddowntime, 
					predowntimeNo+ ";" + textBox_adddowntimeNo.Text + ";" + textBox_addstopType.Text + ";" + textBox_addmachineNo.Text + 
					";" + starttime + ";" + endtime + ";" + textBox_addserviceTeam.Text + ";"+ textBox_addstopReason.Text + 
					";" + textBox_addstatus.Text + ";" + textBox_adddownComment.Text+";" + USER_TABLE.user_Name+";"+ USER_TABLE.user_No);
			}
			catch (Exception ex)
			{
				LogHelper.WriteLog("btn_saveAddDowntime_Click", ex);
			}
		}
		/// <summary>
		/// close popup_downtime
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btn_closeAddDowntime_Click(object sender, RoutedEventArgs e)
		{
			popup_AddDownTime.IsOpen = false;
		}
		#endregion

		#region Popup_DownTime Dragable
		bool isDownPopup_DownTime;
		Point originalPointPopup_DownTime;

		public Point OriginalPointPopup_DownTime { get => originalPointPopup_DownTime; set => originalPointPopup_DownTime = value; }
		public bool IsDownPopup_DownTime { get => isDownPopup_DownTime; set => isDownPopup_DownTime = value; }
		private void btn_Popup_DownTime_ChangePosition_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			IsDownPopup_DownTime = true;
			OriginalPointPopup_DownTime = e.GetPosition(popup_DownTime);
		}

		private void btn_Popup_DownTime_ChangePosition_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			IsDownPopup_DownTime = false;
		}

		private void btn_Popup_DownTime_ChangePosition_PreviewMouseMove(object sender, MouseEventArgs e)
		{
			if (IsDownPopup_DownTime)
			{
				Point pos = e.GetPosition(popup_DownTime);
				popup_DownTime.HorizontalOffset += pos.X - OriginalPointPopup_DownTime.X;
				popup_DownTime.VerticalOffset += pos.Y - OriginalPointPopup_DownTime.Y;
				OriginalPointPopup_DownTime = pos;
			}
		}
		#endregion
		#region Popup_AddDownTime Dragable
		bool isDownPopup_AddDownTime;
		Point originalPointPopup_AddDownTime;
		public Point OriginalPointPopup_AddDownTime { get => originalPointPopup_AddDownTime; set => originalPointPopup_AddDownTime = value; }
		public bool IsDownPopup_AddDownTime { get => isDownPopup_AddDownTime; set => isDownPopup_AddDownTime = value; }
		
		private void btn_Popup_AddDownTime_ChangePosition_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			IsDownPopup_AddDownTime = true;
			OriginalPointPopup_AddDownTime = e.GetPosition(popup_AddDownTime);
		}
		
		private void btn_Popup_AddDownTime_ChangePosition_PreviewMouseMove(object sender, MouseEventArgs e)
		{
			if (IsDownPopup_AddDownTime)
			{
				Point pos = e.GetPosition(popup_AddDownTime);
				popup_AddDownTime.HorizontalOffset += pos.X - OriginalPointPopup_AddDownTime.X;
				popup_AddDownTime.VerticalOffset += pos.Y - OriginalPointPopup_AddDownTime.Y;
				OriginalPointPopup_AddDownTime = pos;
			}
		}
		
		private void btn_Popup_AddDownTime_ChangePosition_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
		{
			IsDownPopup_AddDownTime = false;
		}
		#endregion

		/// <summary>
		/// after selecting the input box,the mouse focus falls on the input box
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void textBox_addstopType_SelectionChanged(object sender, RoutedEventArgs e)
		{
			ComboBox_Shift.Focus();
			textBox_addstopType.Focus();
		}
		/// <summary>
		/// after selecting the input box,the mouse focus falls on the input box
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void textBox_addmachineNo_SelectionChanged(object sender, RoutedEventArgs e)
		{
			ComboBox_Shift.Focus();
			textBox_addmachineNo.Focus();
		}
		/// <summary>
		/// after selecting the input box,the mouse focus falls on the input box
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void textBox_addserviceTeam_SelectionChanged(object sender, RoutedEventArgs e)
		{
			ComboBox_Shift.Focus();
			textBox_addserviceTeam.Focus();
		}
		/// <summary>
		/// after selecting the input box,the mouse focus falls on the input box
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void textBox_addstopReason_SelectionChanged(object sender, RoutedEventArgs e)
		{
			ComboBox_Shift.Focus();
			textBox_addstopReason.Focus();
		}
		/// <summary>
		/// after selecting the input box,the mouse focus falls on the input box
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void textBox_adddownComment_SelectionChanged(object sender, RoutedEventArgs e)
		{
			ComboBox_Shift.Focus();
			textBox_adddownComment.Focus();
		}
		/// <summary>
		/// after selecting the input box,the mouse focus falls on the input box
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void textBox_addstatus_SelectionChanged(object sender, RoutedEventArgs e)
		{
			ComboBox_Shift.Focus();
			textBox_addstatus.Focus();
		}
	}
}
